package com.yungee.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author ruoyi
 **/
@Slf4j
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    // 队列最大长度
    private int queueCapacity = 200;

    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 2;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int processors = Runtime.getRuntime().availableProcessors();
        log.info("运行环境的cpu核心数为:{}",processors);
        executor.setMaxPoolSize(processors*2);
        executor.setCorePoolSize(processors+1);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //此配置代表线程池中的 corePoolSize 数量的线程不会因为闲置而销毁，永远保持活动状态。
        executor.setAllowCoreThreadTimeOut(false);
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        return executor;
    }
}
